﻿/// <reference path="jquery-1.7.1.js" />

//////////////////////////////////////////////////////////////////////////
// AralNovel BGM class
//////////////////////////////////////////////////////////////////////////

function ANBGM(_novel) {
	this.novel = _novel;
	var $test_audio = $("<audio></audio>");
	var _bAudioSupport = ($test_audio[0].play) ? true : false;
	$test_audio.remove();

	var _elemEMBED = null;
	var _objAudio = null;
	var _srcUrl = undefined;
	var _nVolume = 1;
	var _bIsStoped = true;

	// Play BGM file
	this.play = function (_src) {

		// Without url
		if (!_src) {
			if (_srcUrl) {
				// play existing one
				_src = _srcUrl;
			}
			else {
				return;
			}
		}

		this.stop();

		// for MIDI files
		if (_bAudioSupport == false || (/[(.mid)|(.midi)]$/i).test(_src)) {
			if (!_elemEMBED) _elemEMBED = document.createElement("embed");
			_elemEMBED.setAttribute("autostart", true);
			_elemEMBED.setAttribute("hidden", true);
			_elemEMBED.setAttribute("loop", true);
			_elemEMBED.setAttribute("src", _src);
			document.body.appendChild(_elemEMBED);
		}
		// for general audio files
		else {
			if (!_objAudio) _objAudio = document.createElement("audio");
			_objAudio.loop = true;
			_objAudio.src = _src;
			_objAudio.play();
		}

		_srcUrl = _src;
		_bIsStoped = false;
		this.setVolume(_nVolume);
	}

	// Stop BGM file
	this.stop = function () {

		// for MIDI files
		if (_bAudioSupport == false || (/[(.mid)|(.midi)]$/i).test(_srcUrl) && _elemEMBED) {
			try {
				document.body.removeChild(_elemEMBED);
				_elemEMBED.removeNode(true);
			} catch (ex1) { }
			_elemEMBED = null;
		}
		// for general audio files
		else if (_objAudio && _objAudio.pause) {
			_objAudio.pause();
		}

		_bIsStoped = true;
	}

	// Get resource url
	this.getSrc = function () {
		return _srcUrl;
	}

	// isStoped
	this.isStoped = function () {
		return _bIsStoped;		
	}

	// Get current volume
	this.getVolume = function () {
		return _nVolume;
	}

	// Set volume
	this.setVolume = function (vol) {

		_nVolume = (vol < 0 ? 0 : vol);
		_nVolume = (_nVolume > 1 ? 1 : _nVolume);

		// for MIDI files
		if (_elemEMBED && (_bAudioSupport == false || (/[(.mid)|(.midi)]$/i).test(_srcUrl))) {
			_elemEMBED.setAttribute("volume", Math.floor(_nVolume * this.novel.config.bgmVolume));
		}
		// for general audio files
		else if (_objAudio) {
			_objAudio.volume = _nVolume * this.novel.config.bgmVolume / 100;
		}
	}

}; // end of ANBGM class

//